package zheezes.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtil {
	/**
	 * delete directory
	 * 
	 * @param dir
	 *            the directory to be delete
	 * @return true if file is not exist or file be delete, false when file
	 *         can't be delete or a file in the directory can't be delete
	 */
	public static final boolean delete(File file) {
		if (!file.exists()) {
			return true;
		}
		if (file.isDirectory()) {
			for (File f : file.listFiles()) {
				if (!delete(f)) {
					return false;
				}
			}
		}
		return file.delete();
	}

	public final static boolean copyFile(File dest, File src) {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(src);
			out = new FileOutputStream(dest);
		} catch (FileNotFoundException e) {
			try {
				// don't need to check var out is null or not, it must be null
				if (in != null) {
					in.close();
				}
			} catch (IOException e1) {
			}
			return false;
		}
		byte[] buffer = new byte[8096];
		int len = 0;
		try {
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (IOException e) {
			dest.delete();
			return false;
		} finally {
			try {
				out.flush();
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return true;
	}

	public final static boolean copy(File dest, File src) {
		if (src.isFile()) {
			return copyFile(dest, src);
		} else {
			return false;
		}
	}
	
	public final static String getRelativePath(String base, String target, String separator) {
		StringBuilder sb = new StringBuilder();
		String regex = separator;
		if (regex.equals("\\")) {
			regex = "\\\\";
		}
		String[] bs = base.split(regex);
		String[] ts = target.split(regex);

		int i = 0;
		for (i = 0; i < bs.length && i < ts.length; i++) {
			if (!bs[i].equals(ts[i])) {
				break;
			}
		}
		for (int j = 0; j < bs.length - i; j++) {
			sb.append(".." + separator);
		}
		for (; i < ts.length; i++) {
			sb.append(ts[i] + separator);
		}
		if(sb.length() > 0) {
			sb.deleteCharAt(sb.length() - 1);
		}
		System.out.println(sb.toString());
		return sb.toString();
	}
	
	public static void main(String[] args) {
		File base = new File("D:/workspace/eisp-toolkit");
		File target = new File("D:/workspace/eisp-toolkit/lib/dom4j.jar");
		
		File file = new File(base, getRelativePath(base.getAbsolutePath(), target.getAbsolutePath(), File.separator));
		try {
			System.out.println(file.getCanonicalPath());
			System.out.println(target.getCanonicalPath());
			System.out.println(target.getCanonicalPath().equals(file.getCanonicalPath()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
